package com.mayikt.member.controller;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.mayikt.base.BaseResponse;
import com.mayikt.base.BaseWebController;
import com.mayikt.constants.Constants;
import com.mayikt.feign.QQAuthorServiceFeign;
import com.mayikt.web.util.CookieUtils;
import com.qq.connect.QQConnectException;
import com.qq.connect.api.OpenID;
import com.qq.connect.api.qzone.UserInfo;
import com.qq.connect.javabeans.AccessToken;
import com.qq.connect.javabeans.qzone.UserInfoBean;
import com.qq.connect.oauth.Oauth;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

//本地联系修改host文件映射本地域名，不然回调地址回调拿不到accessToken
// （因为域名不一致的问题：导致session不一致）
@Controller
@Slf4j
public class QQAuthoriController extends BaseWebController {
    protected static final Logger logger = LoggerFactory.getLogger(QQAuthoriController.class);
    protected static final String MB_QQ_QQLOGIN_FTL = "member/qqlogin";
    protected static final String REDIRECT_INDEX = "redirect:/";
    @Autowired
    private QQAuthorServiceFeign qqAuthorServiceFeign;
    /**
     * 生成授权链接
     * @param request
     * @return
     */
    @RequestMapping("/qqAuth")
    public String qqAuth(HttpServletRequest request){
        try {
            String authorizeURL = new Oauth().getAuthorizeURL(request);
            logger.info("authorizeURL:{}",authorizeURL);
            return "redirect:" + authorizeURL;
        } catch (QQConnectException e) {
            return ERROR_500_FTL;
        }
    }

    public String qqLoginBack(HttpServletRequest request, HttpServletResponse response, String code){

        try {
            //1.获取用户accessToken
            AccessToken accessTokenObj = new Oauth().getAccessTokenByRequest(request);
            if (null == accessTokenObj) {
                return ERROR_500_FTL;
            }
            String accessToken = accessTokenObj.getAccessToken();
            if (StrUtil.isEmpty(accessToken)) {
                return ERROR_500_FTL;
            }
            //获取用户OpenId
            OpenID openIdObj = new OpenID(accessToken);
            String openId = openIdObj.getUserOpenID();
            if (StrUtil.isEmpty(openId)) {
                return ERROR_500_FTL;
            }
            //根据openId获取用户信息
            BaseResponse<JSONObject> result = qqAuthorServiceFeign.getUserByOpenId(openId);
            if (Constants.HTTP_RES_ERROR_CODE_203.equals(result.getCode())){
                //如果用户不存在，跳转到关联账号页面
                UserInfo userInfoObj = new UserInfo(accessToken, openId);
                UserInfoBean userInfo = userInfoObj.getUserInfo();
                if (null == userInfo){
                    return ERROR_500_FTL;
                }
                String avatarURL100 = userInfo.getAvatar().getAvatarURL100();
                request.setAttribute("avatarURL100",avatarURL100);
                CookieUtils.setCookie(request,response, "qqOpenId",openId);
                return MB_QQ_QQLOGIN_FTL;
            }
            //用户存在
            String token = result.getData().getString("token");
            CookieUtils.setCookie(request,response, com.mayikt.web.constants.Constants.LOGIN_TOKEN_COOKIENAME,token);
            return REDIRECT_INDEX;
            //获取用户信息
        } catch (Exception e) {
            return ERROR_500_FTL;
        }
    }
}
